package team.mai.antexpress.filters;

import com.sun.org.apache.xpath.internal.operations.Bool;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(filterName = "LoginFilter", urlPatterns = {"/admin/*", "/bills/*"})
public class LoginFilter implements Filter {
	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
		//If is a http request, validate login
		if (req instanceof HttpServletRequest) {
			HttpServletRequest request = (HttpServletRequest) req;
			HttpServletResponse response = (HttpServletResponse) resp;
			//verify if session attribute login == true
			if (request.getSession().getAttribute("login") == (Boolean)true) {
				chain.doFilter(req, resp);
			} else {
				response.sendRedirect("/login");
			}
		} else {
			//if not a http request, print an error to output.
			PrintWriter out = resp.getWriter();
			out.print("Not Supported");
		}
	}

	public void init(FilterConfig config) throws ServletException {

	}

}
